
import Singleton from "../Base/Singleton";
import { ApiMsgEnum, IApiPlayerJoinReq } from "../Common";
import { Connection } from "../Core";
import { Player } from "./Player";
import { PlayerManager } from "./PlayerManager";
import { Room } from "./Room";
/**
 * 管理所有房间
 */
export class RoomManager extends Singleton {
    static get Instance() {
        return super.GetInstance<RoomManager>();
    }

    nextRoomId  =1
    //set和map的时间复杂度是o(1)，如果用数组来存，遍历数组时的时间复杂度是o(n)，这里属于用空间换时间
    //并且set集合会自动去重，所以可以防止player被重复推进集合
    rooms:Set<Room> = new Set()
    idMapRoom:Map<number,Room> = new Map()

    createRoom(){
        const room = new Room(this.nextRoomId++)
        this.rooms.add(room)
        this.idMapRoom.set(room.id,room)
        return room
    }
    /**
     * 
     * @param rid 
     * @param uid 
     * @returns 房间id和房间内玩家
     */
    joinRoom(rid:number,uid:number){
        const room=this.idMapRoom.get(rid)
        
        if(room){
            room.join(uid)
            return room
        }
    }
    /**
     * 离开房间
     * @param rid 
     * @param uid 
     * @returns 
     */
    leaveRoom(rid:number,uid:number){
        const room=this.idMapRoom.get(rid)  
        if(room){
            room.leave(uid)
            return room
        }
    }
    /**
     * 关闭房间
     * @param rid 
     */
    closeRoom(rid:number){
        const room = this.idMapRoom.get(rid)
        if(room){
            room.close()
            this.rooms.delete(room)
            this.idMapRoom.delete(rid)         
        }
    }
    /**
     * 房间开始
     * @param rid 
     */
    startRoom(rid:number){
        const room = this.idMapRoom.get(rid)
        if(room){
            room.start()    
        }
    }
    // removePlayer(pid:number){
    //     const player = this.idMapPlayer.get(pid)
    //     if(player){
    //         this.players.delete(player)
    //         this.idMapPlayer.delete(player.id)
    //     }
    // }

    // getPlayer(pid:number){
    //     return this.idMapPlayer.get(pid)
    // }

    /**
     * 获取所有房间
     */
    getRoomsView(rooms:Set<Room> = this.rooms){
        return [...rooms].map((p)=>this.getRoomView(p))
    }

    /**
     * 获取房间视图
     * 返回房间id和房间内所有玩家的id，昵称，rid
     * @param Room 
     * @returns 房间id和房间内所有玩家的id，昵称，rid
     */
    getRoomView({id,players}:Room){
        return{
            id,
            players:PlayerManager.Instance.getPlayersView(players)
        }
    }
    
    /**
     * 大厅给已经存在的玩家同步房间信息
     */
    syncRooms(){
        for (const player of PlayerManager.Instance.players) {
            player.connection.sendMsg(ApiMsgEnum.MsgRoomList,{
                list:this.getRoomsView()
            })
        }
    }
    /**
     * 房间内同步消息
     */
    syncRoom(rid:number){
        const room = this.idMapRoom.get(rid)
        if(room){
            room.sync()
        }
    }
}
